'use client';

import Link from 'next/link';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import type { Trip } from '@prisma/client';
import { useState } from 'react';

type TripWithDetails = Trip & {
  _count: {
    activities: number;
    savedBy: number;
    comments: number;
  };
  user: {
    name: string | null;
    username: string;
  };
};

interface TripListProps {
  trips: TripWithDetails[];
}

export function TripList({ trips: initialTrips }: TripListProps) {
  const [trips, setTrips] = useState(initialTrips);
  const [isDeleting, setIsDeleting] = useState<string | null>(null);
  const [isUpdating, setIsUpdating] = useState<string | null>(null);

  const handleDelete = async (tripId: string) => {
    if (!confirm('确定要删除这个行程吗？')) return;
    
    setIsDeleting(tripId);
    try {
      const response = await fetch(`/api/trips/${tripId}`, {
        method: 'DELETE',
      });
      
      if (!response.ok) {
        throw new Error('删除失败');
      }
      
      // 从本地状态中移除被删除的行程
      setTrips(trips.filter(trip => trip.id !== tripId));
    } catch (error) {
      alert('删除失败: ' + (error as Error).message);
    } finally {
      setIsDeleting(null);
    }
  };

  const handleTogglePublic = async (tripId: string, currentStatus: boolean) => {
    setIsUpdating(tripId);
    try {
      const response = await fetch(`/api/trips/${tripId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          isPublic: !currentStatus,
        }),
      });
      
      if (!response.ok) {
        throw new Error('更新失败');
      }

      // 更新本地状态
      setTrips(trips.map(trip => 
        trip.id === tripId 
          ? { ...trip, isPublic: !currentStatus }
          : trip
      ));
    } catch (error) {
      alert('更新失败: ' + (error as Error).message);
    } finally {
      setIsUpdating(null);
    }
  };

  return (
    <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
      {trips.map((trip) => (
        <div key={trip.id} className="bg-white rounded-lg shadow-lg border border-gray-200">
          <div className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold text-gray-900">
                {trip.title}
              </h2>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => handleTogglePublic(trip.id, trip.isPublic)}
                  disabled={isUpdating === trip.id}
                  className={`px-2 py-1 text-xs font-medium rounded-full transition-colors ${
                    trip.isPublic 
                      ? 'text-blue-600 bg-blue-50 hover:bg-blue-100' 
                      : 'text-gray-600 bg-gray-100 hover:bg-gray-200'
                  }`}
                >
                  {isUpdating === trip.id ? '更新中...' : (trip.isPublic ? '已公开' : '未公开')}
                </button>
              </div>
            </div>
            
            <div className="space-y-3">
              <div className="flex items-center text-gray-600">
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth={2} 
                    d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" 
                  />
                </svg>
                <span className="text-sm">
                  {format(new Date(trip.startDate), 'MM月dd日', { locale: zhCN })} - {format(new Date(trip.endDate), 'MM月dd日', { locale: zhCN })}
                </span>
              </div>
              
              <div className="flex items-center text-gray-600">
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth={2} 
                    d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" 
                  />
                </svg>
                <span className="text-sm">
                  {trip._count.activities} 个活动
                </span>
              </div>

              <div className="flex items-center text-gray-600">
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth={2} 
                    d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" 
                  />
                </svg>
                <span className="text-sm">
                  {trip._count.comments} 条评论
                </span>
              </div>
            </div>
          </div>
          
          <div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
            <div className="flex justify-between items-center">
              <span className="text-sm text-gray-500">
                {format(new Date(trip.createdAt), 'yyyy年MM月dd日', { locale: zhCN })} 创建
              </span>
              <div className="flex items-center space-x-4">
                <Link
                  href={`/trips/${trip.id}/edit`}
                  className="text-blue-600 hover:text-blue-700 transition-colors"
                >
                  编辑
                </Link>
                <button
                  onClick={() => handleDelete(trip.id)}
                  disabled={isDeleting === trip.id}
                  className="text-red-600 hover:text-red-700 transition-colors disabled:opacity-50"
                >
                  {isDeleting === trip.id ? '删除中...' : '删除'}
                </button>
                <Link
                  href={`/trips/${trip.id}`}
                  className="inline-flex items-center text-blue-600 text-sm font-medium hover:text-blue-700 transition-colors"
                >
                  查看详情
                  <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </Link>
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
} 